package com.tx.studentManager.controller;

import java.util.LinkedList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.tx.common.format.util.DateUtil;
import com.tx.studentManager.config.SystemConfig;
import com.tx.studentManager.model.ErrorInfo;
import com.tx.studentManager.model.Page;
import com.tx.studentManager.model.Role;
import com.tx.studentManager.model.User;
import com.tx.studentManager.qo.UserQO;
import com.tx.studentManager.service.RoleService;
import com.tx.studentManager.service.UserService;
import com.tx.studentManager.utils.Constants;
import com.tx.studentManager.utils.DWZJsonUtil;

/**
 * 
 * @描述 用户控制action
 * @since showlove 1.0
 * @version 1.0 2015-8-26 下午5:25:55
 * @author 此生唯晴
 */
@Controller
@RequestMapping("admin/user")
public class UserController {

	@Autowired
	private UserService userService;
	@Autowired
	private RoleService roleService;
	@Autowired
	private SystemConfig systemConfig;

	/**
	 * 
	 * 查询用户
	 * 
	 * @param qo
	 *            查询条件
	 * @param createDateStartStr
	 *            查询用户创建起始日期
	 * @param createDateEndStr
	 *            查询用户创建的结束日期
	 * @param pageSize
	 *            分页大小
	 * @param pageNo
	 *            当前页
	 * @return 分页对象
	 */
	@RequestMapping(value = "/list")
	public ModelAndView userList(
			@ModelAttribute UserQO qo,
			@RequestParam(required = false) String createDateStartStr,
			@RequestParam(required = false) String createDateEndStr,
			@RequestParam(required = false, value = "numPerPage") Integer pageSize,
			@RequestParam(required = false, value = "pageNum") Integer pageNo) {
		if (StringUtils.isNotBlank(createDateEndStr)) {
			qo.setCreateDateEnd(DateUtil.str2DateTime(createDateEndStr));
		}
		if (StringUtils.isNotBlank(createDateStartStr)) {
			qo.setCreateDateStart(DateUtil.str2DateTime(createDateStartStr));
		}
		// 默认查询第一页，每页10条数据
		pageSize = pageSize == null ? systemConfig.getQueryPageSize() : pageSize;
		pageNo = pageNo == null ? 1 : pageNo;
		List<Role> roles = roleService.findAll();
		// 初始化roles
		qo.setInitAll(true);
		Page page = new Page();
		ModelAndView modelAndView = new ModelAndView();
		page.setPageNo(pageNo);
		page.setPageSize(pageSize);
		page.setCondition(qo);
		page = userService.list(page);
		// List<User> list = userService.list(qo);
		modelAndView.addObject("page", page);
		modelAndView.addObject("roleList", roles);
		modelAndView.setViewName("admin/system/user/userList");
		return modelAndView;
	}

	/**
	 * 
	 * 删除用户
	 * 
	 * @param userId
	 *            用户主键
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/delUser", produces = "text/html;charset=UTF-8")
	public String delete(Integer userId) {
		User user = userService.load(userId);
		if (user == null) {
			return DWZJsonUtil.simpleJsonStr(DWZJsonUtil.RESULT_FAILURE_CODE,
					"操作失败,用户不存在", "", "");
		}
		if (userService.delete(userId)) {
			return DWZJsonUtil.simpleJsonStr(DWZJsonUtil.RESULT_SUCCESS_CODE,
					"删除成功", "", "userManager");
		} else {
			return DWZJsonUtil.simpleJsonStr(DWZJsonUtil.RESULT_FAILURE_CODE,
					"操作失败", "", "userManager");
		}
	}
	/**
	 * 
	 * @描述 返回修改密码页面 
	 * @return
	 */
	@RequestMapping("/editPass")
	public String editPass(){
		
		return "admin/updatePassword";
	}
	/**
	 * 
	 * @描述 修改当前登录用户密码
	 * @param newPW
	 * @param oldP
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/updateUserPass", produces = "text/html;charset=UTF-8")
	public String modifyPass(HttpServletRequest request, 
			@RequestParam(required = true) String newPW, 
			@RequestParam(required = true) String oldPW) {
		User currentUser = (User) request.getSession().getAttribute(Constants.USER_SESSION_NAME);
		if (!oldPW.equals(currentUser.getPassword())) {
			return DWZJsonUtil.simpleJsonStr(DWZJsonUtil.RESULT_FAILURE_CODE, "原密码错误！", "", null);
		}else{
			String hql="update user u set u.password=? where u.userId=?";
			Object params[]=new Object[2];
			params[0]=newPW;
			params[1]=currentUser.getUserId();
			if(!(userService.batchExecuteWithSql(hql, params)>0))
				return DWZJsonUtil.simpleJsonStr(DWZJsonUtil.RESULT_FAILURE_CODE, "修改失败", null, null);
			return DWZJsonUtil.simpleJsonStr(DWZJsonUtil.RESULT_SUCCESS_CODE, "修改成功", DWZJsonUtil.OPER_CLOSE_CURRENT, null);
		}
	}
	/**
	 * 
	 * 删除多个用户
	 * 
	 * @param userId
	 *            用户主键
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/delete", produces = "text/html;charset=UTF-8")
	public String delete(@RequestParam List<Integer> ids) {
		List<User> list=new LinkedList<>();
		for (Integer id : ids) {
			User user =new User();
			user.setUserId(id);
			list.add(user);
		}
		if (!userService.deleteAll(list)) {
			return DWZJsonUtil.simpleJsonStr(DWZJsonUtil.RESULT_FAILURE_CODE,
					"操作失败！", "", "");
		}
//		String hql="delete from User u where u.userId in(:list)";
//		userService.batchExecuteWithHql(hql, ids);
		return DWZJsonUtil.simpleJsonStr(DWZJsonUtil.RESULT_SUCCESS_CODE,
				"操作成功,"+ids.size()+"个用户被删除", "", "userManager");
	}

	/**
	 * 
	 * 查询用户信息，返回用户编辑页面
	 * 
	 * @param userId
	 * @return
	 */
	@RequestMapping(value = "/modifyUser")
	public ModelAndView modifyUser(Integer userId) {
		User user = userService.load(userId);
		ModelAndView modelAndView = new ModelAndView();
		if (user == null) {
			ErrorInfo errorInfo = new ErrorInfo();
			errorInfo.setErrorCode("用户不存在，请查正再试！");
			modelAndView.setViewName("");
			modelAndView.addObject("errorInfo", errorInfo);
		} else {
			user = userService.findById(userId, true);
			modelAndView.addObject("user", user);
			modelAndView.addObject("roleList", roleService.findAll());
			modelAndView.setViewName("admin/system/user/userUpdate");
		}
		return modelAndView;
	}

	/**
	 * 
	 * 添加用户，返回视图
	 * 
	 * @param modelAndView
	 * @return
	 */
	@RequestMapping(value = "/addUser")
	public ModelAndView addUser(ModelAndView modelAndView) {
		modelAndView.setViewName("admin/system/user/userAdd");
		List<Role> roles = roleService.findAll();
		modelAndView.addObject("roleList", roles);
		return modelAndView;
	}

	/**
	 * 
	 * 添加用户
	 * 
	 * @param user
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/toAddUser", produces = "text/html;charset=UTF-8")
	public String toAddUser(@ModelAttribute User user, Integer roleId) {
		Role role = null;
		if (roleId != null) {
			role = roleService.findById(roleId);
		}
		if (role != null) {
			user.setRole(role);
		}
		user = userService.insert(user);
		if (user != null) {
			return DWZJsonUtil.simpleJsonStr("200", "添加用户成功",
					DWZJsonUtil.OPER_CLOSE_CURRENT, "userManager");
		} else {
			return DWZJsonUtil.simpleJsonStr("301", "添加用户失败",
					DWZJsonUtil.OPER_CLOSE_CURRENT, null);
		}

	}

	/**
	 * 
	 * 执行用户修改
	 * 
	 * @param user
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/toModifyUser", produces = "text/html;charset=UTF-8")
	public String toModifyUser(User user, Role role, String createDateStr) {
		if (role.getRoleId() != null) {
			// 更新角色
			role = roleService.findById(role.getRoleId());
			user.setRole(role);
		}
		if (userService.updateNotNull(user)) {
			return DWZJsonUtil.simpleJsonStr("200", "更新成功",
					DWZJsonUtil.OPER_CLOSE_CURRENT, "userManager");
		}
		return DWZJsonUtil.simpleJsonStr("300", "操作失败",
				DWZJsonUtil.OPER_CLOSE_CURRENT, null);
	}

	/**
	 * 
	 * 启用和禁用用户
	 * 
	 * @param oper
	 *            必需，1表示禁用，0表示启用
	 * @param userId
	 *            必需，操作用户ID
	 * @return json
	 */
	@ResponseBody
	@RequestMapping(value = "/useOrNot", produces = "text/html;charset=UTF-8")
	public String useOrNot(@RequestParam(required = true) Integer oper,
			Integer userId) {
		User user = userService.load(userId);
		String sql = "update user set activated=? where userId=?";
		if (user == null) {
			return DWZJsonUtil.simpleJsonStr("300", "操作失败，用户不存在！", null, null);
		}
		Object[] params = new Object[2];
		params[1] = userId;
		// 禁用用户
		if (oper == 0) {
			params[0] = 0;
		} else if (oper == 1) {
			// 启用
			params[0] = 1;
		}

		int result = userService.batchExecuteWithSql(sql, params);
		if (result > 0) {
			return DWZJsonUtil.simpleJsonStr("200", "操作成功", null, null);
		} else {
			return DWZJsonUtil.simpleJsonStr("300", "操作失败", null, null);
		}
	}
}
